import requests

def download_file_with_progress(url, local_filename):
    # 发起HEAD请求以获取文件大小
    response = requests.head(url)
    file_size = int(response.headers.get('Content-Length', 0))  # 如果没有Content-Length，默认为0

    # 发起GET请求
    with requests.get(url, stream=True) as response:
        response.raise_for_status()  # 检查请求是否成功

        total_size = file_size  # 总文件大小
        downloaded = 0  # 已下载的字节数

        with open(local_filename, 'wb') as file:
            for chunk in response.iter_content(chunk_size=1024):
                if chunk:  # 过滤掉保持连接的chunk
                    file.write(chunk)
                    downloaded += len(chunk)  # 更新已下载的字节数
                    progress = (downloaded / total_size) * 100 if total_size > 0 else 0
                    yield round(progress, 2)  # 产生进度百分比，保留两位小数

# 使用示例
file_url = 'https://pan.miaoi.top/f/6nNT1/A.%E4%B8%AD%E4%B8%96%E7%BA%AA%E5%B0%8F%E9%95%87%E5%BB%BA%E9%80%A0%E8%AE%A1%E5%88%92.mcworld'  # 文件的URL
local_file_path = 'somefile.zip'  # 本地保存的文件名

# 创建下载生成器
download_progress = download_file_with_progress(file_url, local_file_path)

# 循环遍历进度生成器，并打印进度值
for progress in download_progress:
    print(f'当前下载进度：{progress}%')

# 确保打印最终的下载完成信息
print(f'文件已下载到：{local_file_path}')